// import isUTF8 from "is-utf8"
import {read, utils, WorkBook} from "xlsx"
import cptable from "codepage"
import {ElMessage} from "element-plus";
import {createBiochemicalCloud, IBiochemical} from "@/model/TerminalType";
import dayjs from "dayjs";
import isUTF8 from "is-utf8";

export const transformFromCSV = async (file: File): Promise<Array<any> | null> => {
  const isCSV = file.name.split(".").reverse()[0].toLowerCase() === "csv"
  if (!isCSV) {
    ElMessage.error("文件类型选择错误")
    return null
  }
  const bufferData = await file.arrayBuffer()
  console.log(bufferData)
  const U8A = new Uint8Array(bufferData)
  const f = isUTF8(U8A)
  let workbooks: WorkBook
  console.log(f)
  if (f) {
    workbooks = read(bufferData, {cellDates: true})
  } else {
    workbooks = read(cptable.utils.decode(936, U8A), {type: "string", cellDates: true})
  }
  const json = utils.sheet_to_json(workbooks.Sheets[workbooks.SheetNames[0]])
  return json
}

export const transformFromXlsb = async (file: File): Promise<Array<any>> => {
  const isXlsb = file.name.split(".").reverse()[0].toLowerCase() === "xlsb"
  if (!isXlsb) {
    ElMessage.error("文件类型选择错误")
    return []
  }
  const bufferData = await file.arrayBuffer()
  console.log(bufferData)
  try {
    // const workbook = read(isUtf8File ? bufferData : cptable.utils.decode(936, buf), { type: isUtf8File ? "array" : 'string',cellDates:true});
    const workbook = read(bufferData, {type: 'binary', cellDates: true, codepage: 936});
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    // const header = this.getHeaderRow(worksheet);
    const results = utils.sheet_to_json(worksheet);
    return transformXlsbToJson(results)
  } catch (e) {
    console.error(e)
  }
  return []

}
const transformXlsbToJson = (array: Array<any>) => {
  const header = array[0];
  const data: Array<any> = [];
  for (let i = 1; i < array.length; i++) {
    const item = array[i];
    const itemData = {};
    Object.keys(item).forEach(d => {
      itemData[header[d]] = item[d];
    })
    data.push(itemData)
  }
  return data;


}

export const formDataFromEqu = (json: Array<any>): Array<any> => {
  return json
}
export const csvTransform = (csvRows: Array<any>): Array<IBiochemical> => {
  return csvRows.map(item => {
    let newVar: IBiochemical = {
      pltMessage: item["PLT Message"],
      rbcMessage: item["RBC Message"],
      wbcMessage: item["WBC Message"],
      Baso: item["Bas# (10^9/L)"],
      Basop: item["Bas% (%)"],
      CRP: "",
      Channel: "",
      Eos: item["Eos# (10^9/L)"],
      Eosp: item["Eos% (%)"],
      Hct: item["HCT (%)"],
      Hgb: item["HGB (g/L)"],
      ID: item["样本编号"],
      Ly: item["Lym# (10^9/L)"],
      Lyp: item["Lym% (%)"],
      Mch: item["MCH (pg)"],
      Mchc: item["MCHC (g/L)"],
      Mcv: item["MCV (fL)"],
      Mo: item["Mon# (10^9/L)"],
      Mop: item["Mon% (%)"],
      Mpv: item["MPV (fL)"],
      Neu: item["Neu# (10^9/L)"],
      Neup: item["Neu% (%)"],
      Pct: item['PCT (%)'],
      Pdw: "",
      Plcc: item['P-LCC (10^9/L)'],
      Plcr: item['P-LCR (%)'],
      Plt: item['PLT (10^9/L)'],
      Rbc: item['RBC (10^12/L)'],
      RbcTime: "",
      Rdw: item["PDW ( )"],
      RdwCV: item["RDW-CV (%)"],
      RdwSD: item["RDW-SD (fL)"],
      Time: dayjs(item["日期"]).format("YYYY-MM-DD") + " " + item["时间"],
      WbcTime: item["WBC (10^9/L)"],
      Wic: "",
      Woc: "",
      WocRealLength: "",
      checkDoctor: item["检验者"],
      hsCRP: ""
    };
    return newVar
  })
}
export const xlsbTransform = (xlsbRows: Array<any>): Array<IBiochemical> => {
  return xlsbRows.map(item => {
    console.log( dayjs(item["日期"]).format("YYYY-MM-DD") + " " + item["时间"])
    let newVar: IBiochemical = {
      Baso: item["BAS%"],
      Basop: "",
      CRP: "",
      Channel: "",
      Eos: "",
      Eosp: item['EOS%'],
      Hct: item['HCT'],
      Hgb: item["HGB"],
      ID: item["样本号"],
      Ly: "",
      Lyp: item["LYM%"],
      Mch: item["MCH"],
      Mchc: item["MCHC"],
      Mcv: item["MCV"],
      Mo: "",
      Mop: item["MON%"],
      Mpv: item["MPV"],
      Neu: "",
      Neup: item["NEU%"],
      Pct: item["PCT"],
      Pdw: item["PDW"],
      Plcc: item["P-LCC"],
      Plcr: item["P-LCR"],
      Plt: item["PLT"],
      Rbc: item["RBC"],
      RbcTime: "",
      Rdw: "",
      RdwCV: item["RDW-CV"],
      RdwSD: item["RDW-SD"],
      Time: dayjs(item["日期"]).format("YYYY-MM-DD") + " " + item["时间"],
      WbcTime: item["WBC"],
      Wic: "",
      Woc: "",
      WocRealLength: "",
      checkDoctor: "",
      hsCRP: "",
      pltMessage: item["PLTFlag"],
      rbcMessage: item["RBCFlag"],
      wbcMessage: item["WBCFlag"],
    };
    return newVar
  })
}

export const transformData: Object = {
  csv: csvTransform,
  xlsb: xlsbTransform

}
export const useTransformByKey = (key?:string) => {
  if (key && transformData.hasOwnProperty(key)) {
    return transformData[key]
  }
  return null
}
